<template>
  <div class="area-code-select" style="width: 100%">
    <el-select v-model="selectedProvince" placeholder="请选择省份" @change="handleProvinceChange" :disabled="disabled"
      :clearable="clearable" style="min-width: 100px">
      <el-option v-for="province in provinceList" :key="province.provinceCode" :label="province.name"
        :value="province.provinceCode" />
    </el-select>

    <el-select v-model="selectedCity" placeholder="请选择城市" @change="handleCityChange"
      :disabled="disabled || !selectedProvince" :clearable="clearable" style="min-width: 100px; margin: 0 10px">
      <el-option v-for="city in cityList" :key="city.cityCode" :label="city.name" :value="city.cityCode" />
    </el-select>

    <el-select v-model="selectedArea" placeholder="请选择区县" @change="handleAreaChange"
      :disabled="disabled || !selectedCity" :clearable="clearable" style="min-width: 100px" v-if="showArea">
      <el-option v-for="area in areaList" :key="area.areaCode" :label="area.name" :value="area.areaCode" />
    </el-select>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import { queryCityDictByProvinceCode, queryAreaDictByCityCode, queryProvinceDict } from '@/api/system'

// Props定义
const props = defineProps<{
  provinceCode?: string
  cityCode?: string
  areaCode?: string
  province?: string
  city?: string
  disabled?: boolean
  clearable?: boolean
  showArea?: boolean
}>()

// Emits定义
const emit = defineEmits<{
  'update:provinceCode': [value: string]
  'update:cityCode': [value: string]
  'update:areaCode': [value: string]
  'update:province': [value: string]
  'update:city': [value: string]
  'change': [value: {
    provinceCode?: string
    cityCode?: string
    areaCode?: string
  }]
}>()

// 响应式数据
const provinceList = ref<Array<{ provinceCode: string; name: string }>>([])
const cityList = ref<Array<{ cityCode: string; name: string }>>([])
const areaList = ref<Array<{ areaCode: string; name: string }>>([])

// 直接使用独立的props值
const selectedProvince = ref(props.provinceCode || '')
const selectedCity = ref(props.cityCode || '')
const selectedArea = ref(props.areaCode || '')
const selectedProvinceName = ref(props.province || '')
const selectedCityName = ref(props.city || '')


// 加载省份数据
const loadProvinces = async () => {
  try {
    const response = await queryProvinceDict()
    provinceList.value = response?.data as Array<{ provinceCode: string; name: string }>
  } catch (error) {
    console.error('获取省份数据失败:', error)
  }
}

// 加载城市数据
const loadCities = async (provinceCode: string) => {
  try {
    const response = await queryCityDictByProvinceCode({ provinceCode })
    cityList.value = response?.data as Array<{ cityCode: string; name: string }>
  } catch (error) {
    console.error('获取城市数据失败:', error)
  }
}

// 加载区县数据
const loadAreas = async (cityCode: string) => {
  try {
    const response = await queryAreaDictByCityCode({ cityCode })
    areaList.value = response?.data as Array<{ areaCode: string; name: string }>
  } catch (error) {
    console.error('获取区县数据失败:', error)
  }
}

// 省份选择变化处理
const handleProvinceChange = (provinceCode: string) => {
  selectedProvince.value = provinceCode
  selectedProvinceName.value = provinceList.value.find(p => p.provinceCode === provinceCode)?.name || ''
  selectedCityName.value = ''
  selectedCity.value = ''
  selectedArea.value = ''
  cityList.value = []
  areaList.value = []

  if (provinceCode) {
    loadCities(provinceCode)
  }

  emitUpdate()
}

// 城市选择变化处理
const handleCityChange = (cityCode: string) => {
  selectedCity.value = cityCode
  selectedCityName.value = cityList.value.find(c => c.cityCode === cityCode)?.name || ''
  selectedArea.value = ''
  areaList.value = []

  if (cityCode) {
    loadAreas(cityCode)
  }

  emitUpdate()
}

// 区县选择变化处理
const handleAreaChange = (areaCode: string) => {
  selectedArea.value = areaCode
  emitUpdate()
}

// 发送更新事件
const emitUpdate = () => {
  const value = {
    provinceCode: selectedProvince.value,
    cityCode: selectedCity.value,
    areaCode: selectedArea.value
  }
  emit('change', value)
  emit('update:provinceCode', selectedProvince.value)
  emit('update:cityCode', selectedCity.value)
  emit('update:areaCode', selectedArea.value)
  emit('update:province', selectedProvinceName.value)
  emit('update:city', selectedCityName.value)
}

// 监听provinceCode变化
watch(() => props.provinceCode, (newValue) => {
  // 只有当值真正改变时才处理，避免循环更新
  if (selectedProvince.value !== newValue && newValue !== undefined) {
    selectedProvince.value = newValue || ''
    // 清空后续选择
    selectedCity.value = ''
    selectedArea.value = ''
    cityList.value = []
    areaList.value = []

    if (newValue) {
      loadCities(newValue).then(() => {
        // 如果cityCode也有外部值，尝试设置城市
        if (props.cityCode && props.cityCode !== selectedCity.value) {
          selectedCity.value = props.cityCode
          loadAreas(props.cityCode).then(() => {
            // 如果areaCode也有外部值，尝试设置区县
            if (props.areaCode && props.areaCode !== selectedArea.value) {
              selectedArea.value = props.areaCode
            }
          })
        }
      })
    }
  }
})

// 监听cityCode变化
watch(() => props.cityCode, (newValue) => {
  if (selectedCity.value !== newValue && newValue !== undefined) {
    selectedCity.value = newValue || ''
    // 清空区县选择
    selectedArea.value = ''
    areaList.value = []

    if (newValue && selectedProvince.value) {
      loadAreas(newValue).then(() => {
        // 如果areaCode也有外部值，尝试设置区县
        if (props.areaCode && props.areaCode !== selectedArea.value) {
          selectedArea.value = props.areaCode
        }
      })
    }
  }
})

// 监听areaCode变化
watch(() => props.areaCode, (newValue) => {
  if (selectedArea.value !== newValue && newValue !== undefined) {
    selectedArea.value = newValue || ''
  }
})

// 组件挂载时加载省份数据
onMounted(() => {
  loadProvinces()

  // 如果初始有值，加载对应的城市和区县
  if (selectedProvince.value) {
    loadCities(selectedProvince.value).then(() => {
      if (selectedCity.value) {
        loadAreas(selectedCity.value)
      }
    })
  }
})
</script>

<style scoped>
.area-code-select {
  display: flex;
  align-items: center;
}
</style>
